<template>
  <div class="lix-container">
    <scroll-view scroll-y style="height: 100%;" @scroll="scroll">
      <div class="lix-dis__item" @click="hiddenInput" v-for="(item, idx) in list" :key="idx">
        <div class="lix-dis__left">
          <image :src="item.user.avatar"/>
        </div>
        <div class="lix-dis__right">
          <div class="nickname">{{ item.user.nickname }}</div>
          <div class="content">{{ item.content }}</div>
          <div class="imgs">
            <image v-for="(img, imgIdx) in item.thumbs" :key="imgIdx" :src="img" @click="previewImage" :data-idx="imgIdx" :data-item="item" />
          </div>
          <div class="middle-control">
            <div class="time">{{ item.publishTime }}</div>
            <image src="../../static/image/wxdiscuss.png" @click.stop="touchDiscuss" :data-name="nickname" :data-idx="idx"/>
          </div>
          <div class="content-view" v-if="item.like_num > 0 || item.comments.length > 0">
            <div class="star-view" v-if="item.like_num > 0">
              <image src="../../static/image/love.png" />
              <div class="star-list" v-for="(name, nameIdx) in item.likes" :key="nameIdx">{{ name }}<span v-if="nameIdx !== item.likes.length - 1">,</span></div>
            </div>
            <div class="comment-list">
              <div class="comment-item" v-for="(comment, comIdx) in item.comments" :key="comIdx">
                <div class="name">{{ comment.nickname }}：<span>{{ comment.content }}</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <ZanLoadmore :loading="loading" :nomore="! hasNextPage" v-if="!noData"/>
    </scroll-view>

    <div :animation="animation" class="lix-dis__pop" :style="{top: popTop + 'px', width: popWidth + 'px'}" v-if="isShow">
      <!-- <button>点赞</button>
      <button>评论</button> -->
      <div class="pop-item" v-if="isShow" @click="bindLike">
        <image src="../../static/image/love-fff.png"/>
        {{ likeText }}
      </div>
      <div v-if="isShow">|</div>
      <div class="pop-item" v-if="isShow" @click="bindReply">
        <image src="../../static/image/discuss-fff.png"/>
        评论
      </div>
    </div>
    <!-- <view class="talk" @click="bindReply">回复</view> -->

    <view class="release" :hidden="!releaseFocus">
        <textarea class="text"
              placeholder-class="input_null"
              fixed="true"
              maxlength="-1"
              show-confirm-bar="false"
              cursor-spacing="15"
              auto-height="true"
              :focus="releaseFocus"
              :placeholder="'回复' + ' ' +releaseName + ':'"
              @input="handleInput"></textarea>
        <view class="submit" @click="submit">发送</view>
    </view>

  </div>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex';
import { DISCOVER_GET_LIST, DISCOVER_POST_LIKE, DISCOVER_POST_COMMENT } from '../../store/mutation-types';
import Tip from '../../utils//tips';
import ZanLoadmore from '../../../node_modules/mpvue-zanui/src/components/zan/loadmore';
import request from '../../utils/wxRequest';

export default {
  components: {
    ZanLoadmore
  },
  computed: {
    ...mapGetters('discover', {
      list: 'list',
      loading: 'loading',
      hasNextPage: 'hasNextPage',
      noData: 'noData',
      currentPage: 'currentPage',
      likeText: 'likeText'
    }),
    ...mapGetters('user', {
      nickname: 'nickname'
    }),
    ...mapGetters('city', {
      defaultCounty: 'defaultCounty',
      currentCityCode: 'currentCityCode',
      code: 'code'
    })
  },
  watch: {
    currentCityCode: function(newValue, oldValue) {
      this.destroyedState();
      this.areaCode = newValue;
      console.log('发现页面属性变动');
      console.log(newValue);
      console.log(oldValue);
      this.getDiscoverList({
        page: 1,
        code: this.areaCode
      });
    },
    code: function(newValue, oldValue) {
      this.destroyedState();
      this.areaCode = newValue;
      console.log('发现页面属性变动');
      console.log(newValue);
      console.log(oldValue);
      this.getDiscoverList({
        page: 1,
        code: this.areaCode
      });
    }
  },
  data() {
    return {
      photoWidth: wx.getSystemInfoSync().windowWidth / 5,

      popTop: 0, // 弹出点赞评论框的位置
      popWidth: 0, // 弹出框宽度
      isShow: false, // 判断是否显示弹出框
      animation: null,
      releaseFocus: false,
      releaseName: null,
      scrollHeight: wx.getSystemInfoSync().windowHeight,
      selectIndex: null,
      commentText: '',
      areaCode: ''
    };
  },
  onLoad() {
    this.checkAuth();
    request.beforeAction()
      .then(token => {
        this.destroyedState();
        // 在有地域code的时候，增加地级市编码参数
        let code = '';
        if (this.areaCode.length > 0) {
          code = this.areaCode;
        }
        this.getDiscoverList({
          page: 1,
          code: code
        });
      });
  },
  onReachBottom() {
    if (this.hasNextPage) {
      request.beforeAction()
        .then(token => {
          // 在有地域code的时候，增加地级市编码参数
          let code = '';
          if (this.areaCode.length > 0) {
            code = this.areaCode;
          }
          this.getDiscoverList({
            page: this.currentPage + 1,
            code: code
          });
        });
    }
  },
  onUnload() {
    console.log('页面卸载');
    this.destroyedState();
  },
  onPullDownRefresh() {
    this.destroyedState();
    request.beforeAction()
      .then(token => {
        // 在有地域code的时候，增加地级市编码参数
        let code = '';
        if (this.areaCode.length > 0) {
          code = this.areaCode;
        }
        this.getDiscoverList({
          page: 1,
          code: code
        }).then((res) => {
          wx.stopPullDownRefresh();
        });
      });
  },
  methods: {
    ...mapActions('discover', {
      'getDiscoverList': DISCOVER_GET_LIST,
      'destroyedState': 'destroyedState',
      'likeAction': DISCOVER_POST_LIKE,
      'postComment': DISCOVER_POST_COMMENT
    }),
    ...mapMutations('discover', {
      'refreshLikeText': 'refreshLikeText'
    }),
    previewImage(e) {
      const item = e.mp.currentTarget.dataset.item;
      const idx = e.mp.currentTarget.dataset.idx;
      wx.previewImage({
        urls: item.pics,
        current: item.pics[idx],
        success: function(res) {
          console.log(res);
        },
        fail: function(e) {
          console.log(e);
        }
      });
    },
    touchDiscuss(e) {
      const idx = e.mp.currentTarget.dataset.idx;
      console.log('弹出的index -> :', idx);
      this.releaseName = e.mp.currentTarget.dataset.name;
      this.popBoxAnimation(e);
    },
    popBoxAnimation(e) {
      const self = this;
      let animation = wx.createAnimation({
        duration: 100,
        timingFunction: 'linear',
        delay: 0
      });
      const idx = e.mp.currentTarget.dataset.idx;
      console.log(idx);

      this.refreshLikeText({index: idx});

      if (this.isShow === false || idx !== this.selectIndex) {
        console.log('弹出');
        this.selectIndex = idx;
        this.popTop = e.mp.target.offsetTop - (e.mp.detail.y - e.mp.target.offsetTop) / 2;
        this.isShow = true;
        setTimeout(function() {
          animation.width(0).opacity(1).step();
          self.popWidth = 130;
          self.animation = animation.export();
        }, 50);
      } else {
        console.log('收回');
        setTimeout(function() {
          animation.width(120).opacity(1).step();
          self.animation = animation.export();
        }, 50);

        self.popTop = e.mp.target.offsetTop - (e.mp.detail.y - e.mp.target.offsetTop) / 2;
        self.popWidth = 0;
        self.isShow = false;
      }
    },
    pushBoxAnimation(e) {
      const self = this;
      let animation = wx.createAnimation({
        duration: 100,
        timingFunction: 'linear',
        delay: 0
      });
      if (this.isShow === false) {
        console.log('弹出');
        this.popTop = e.mp.target.offsetTop - (e.mp.detail.y - e.mp.target.offsetTop) / 2;
        this.isShow = true;
        setTimeout(function() {
          animation.width(0).opacity(1).step();
          self.popWidth = 130;
          self.animation = animation.export();
        }, 50);
      } else {
        console.log('收回');
        setTimeout(function() {
          animation.width(120).opacity(1).step();
          self.animation = animation.export();
        }, 50);

        self.popTop = e.mp.target.offsetTop - (e.mp.detail.y - e.mp.target.offsetTop) / 2;
        self.popWidth = 0;
        self.isShow = false;
      }
    },
    bindReply(e) {
      this.releaseFocus = true;
      const name = this.list[this.selectIndex].user.nickname;
      console.log(this.releaseName);
      console.log(name);
      this.releaseName = name;
      this.pushBoxAnimation(e);
    },
    hiddenInput(e) {
      console.log('hidden input');
      // TODO: 关闭弹窗 点击空白处 有hug
      // if (this.isShow) {
      //   this.pushBoxAnimation(e);
      // }
      this.releaseFocus = false;
    },
    scroll(e) {
      console.log('滚动了');
      console.log(e);
      this.isShow = false;
    },
    bindLike(e) {
      const item = this.list[this.selectIndex];
      console.log(item);
      console.log('点赞按钮触发');
      this.likeAction({
        id: item.id,
        name: this.nickname,
        index: this.selectIndex
      });
    },
    handleInput(e) {
      console.log(e);
      const val = e.mp.detail.value;
      this.commentText = val;
    },
    submit(e) {
      if (this.commentText.length < 1) {
        Tip.error('请不要发空内容');
        return;
      }
      const item = this.list[this.selectIndex];
      console.log(item);
      this.postComment({
        id: item.id,
        content: this.commentText
      });

      this.commentText = '';
      this.hiddenInput();
    },
    // 检查授权页面 弹出授权窗口
    checkAuth() {
      // 查看是否授权
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            console.log('已经授权');
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                console.log(res.userInfo);
              }
            });
          } else {
            console.log('没有授权');
            wx.navigateTo({
              url: '/pages/member/auth'
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
@import "../../theme-chalk/discover.scss";
</style>
